<?php

namespace app\admin\controller\yalimedia;

use addons\yalimedia\library\AlibabaCloundHelper;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\controller\Backend;
use app\admin\model\yalimedia\Category as CategoryModel;
use app\admin\model\yalimedia\Course as CourseModel;


/**
 * 素材管理
 * @icon fa fa-circle-o
 */
class Media extends Backend
{
    protected $noNeedRight = ["tree","upload_tree",'createUploadImage',"createUploadVideo","refreshUploadVideo"];
    public $type = ['2'=>'音频','3'=>'视频','1'=>'图片'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new CategoryModel;
        // $yalimedia = get_addon_config('yalimedia');
        // $config = $yalimedia['ali'];
        // if(empty($config['accessKeyId']) || empty($config['accessKeySecret']) || empty($config['regionId'])){
        //     $this->error(__('请完善阿里云视频点播配置项'),'');
        // }
    }
    
    
    public function index(){
        
        $type   = $this->request->param('type',1);
        $search = $this->request->param('search');
        
        // 素材分类
        $categoryModel = new \app\admin\model\yalimedia\Category();
        
        if ($this->request->isAjax()){
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $categoryModel->where($where)
                ->where(['type'=>$type])
                ->order('id DESC')
                ->paginate($limit);
            
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        
        $this->assign('type',$type);
        return $this->view->fetch();
    }

    public function index2(){
        
        $type   = $this->request->param('type',1);
        $search = $this->request->param('search');
        $categoryModel = new \app\admin\model\yalimedia\Category();
        
        
        $category = $categoryModel->where(['type'=>$type])->find();
        if(!$category = $categoryModel->where(['type'=>$type])->find()){
      
            if(!$cateId = AlibabaCloundHelper::instance()->add_category($this->type[$type],0)){
                $this->error(__('同步阿里云失败，请稍候再试~'));
            }else{
                $categoryModel = new \app\admin\model\yalimedia\Category();
                $categoryModel->save([
                    'cateid'=>$cateId,
                    'type'=>$type
                ]);
            }
        }else{
            $cateId = $category['cateid'];
        }


        if ($this->request->isAjax())
        {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
        
            $cateid = $this->request->get("cateid",$cateId);
            switch($type){
                case "2":
                    $type_name = "audio";
                    break;
                case "3":
                    $type_name = "video";
                    break;
                case "1":
                    $type_name = "image";
                    break;
            }
            $match = "CateId=".$cateid;
            if($search){
                $match.=" and Title = '".$search."'";
            }

            $list = AlibabaCloundHelper::instance()->searchMedia($type_name,$match,($offset/$limit)+1,$limit);
            $total = empty($list->Total)?0:$list->Total;
  

            $list = empty($list->MediaList)?[]:$list->MediaList;

            foreach($list as &$v){

                switch ($v->MediaType){
                    case "audio":
                        $v->AudioTitle   = $v->Audio->Title;
                        $v->Status       = $v->Audio->Status;
                        $v->Size         =  AlibabaCloundHelper::instance()->getFilesize(empty($v->Audio->Size)?0:$v->Audio->Size);
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Audio->CreationTime));
                        break;
                    case "video":
                        $v->VideoTitle   = $v->Video->Title;
                        $v->VideoId      = $v->Video->VideoId;
                        $v->Status       = $v->Video->Status;
                        $v->Size         = empty($v->Video->Size)?'':AlibabaCloundHelper::instance()->getFilesize(empty($v->Video->Size)?0:$v->Video->Size);
                        $v->CoverURL     = empty($v->Video->CoverURL)?'':$v->Video->CoverURL;
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Video->CreationTime));
                        break;
                    case "image":
                        $v->Title        = $v->Image->Title;
                        $v->MediaId      = $v->Image->ImageId;
                        $v->Status       = $v->Image->Status;
                        $v->Size         = empty($v->Image->Size)?'':AlibabaCloundHelper::instance()->getFilesize(empty($v->Image->Size)?0:$v->Image->Size);
                        $v->URL          = empty($v->Image->URL)?'':$v->Image->URL;
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Image->CreationTime));
                        break;
                }
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }


        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);
    

        $chanelList[$cateId] = ['id'=>$cateId,'text'=>"全部视频",'num'=>0,'parent'=>"#",'state'=>['opened'=>true]];
        foreach($list as $k=>$v){
            $chanelList[$v->CateId] = ['id'=>$v->CateId,'text'=>$v->CateName,'num'=>0,'parent'=>"#",'state'=>['opened'=>true]];
        }

        $chanelList = array_values($chanelList);
        $this->assignconfig("channelList", $chanelList);

        $this->assign('type',$type);
        return $this->view->fetch();

    }
    
    
     /**
     * 编辑
     */
    public function add()
    {
        $type = $this->request->param('type',1);
        
        if ($this->request->isPost()) {
            $this->token();
            
            // // 组队添加
            // $data = $this->request->param('');
            // $save = $data['row'];
            
            // $save['admin_id']     = $admin_id;
            // $this->model->allowField(true)->save($save);
        }
        
        $this->assign('type',$type);
        $this->view->assign('groupList', build_select('row[cateid]', CourseModel::column('id,title'),null, ['class' => 'form-control selectpicker']));
        return parent::add();
    }
    
    
    // /**
    //  * 添加
    //  */
    // public function add()
    // {
    //     if ($this->request->isPost()) {
            
    //         // 组队添加
    //         $data = $this->request->param('');
    //         $save = $data['row'];
    //         $save['room_id'] = 'room'.$save['cate_id'].':'.uniqid();
            
    //         $admin_id   = $this->auth->id;
    //         $admin_name = $this->auth->nickname;
    //         $admin_avatar = $this->auth->avatar;
            
    //         $save['admin_id']     = $admin_id;
    //         $save['admin_name']   = $admin_name;
    //         $save['admin_avatar'] = $admin_avatar;
        
                    
    //         $this->model->allowField(true)->save($save);
    //     }
    //     return parent::add();
    // }
    
    
    // /**
    //  * 添加
    //  */
    // public function add()
    // {
       
    //     $cateId     = $this->request->get('cateId');
    //     $cateName   = $this->request->get('cateName',"默认分组");
    //     $type       = $this->request->get('type');

    //     if(empty($cateId)){
    //         $categoryModel = new \app\admin\model\yalimedia\Category();
    //         if(!$category = $categoryModel->where(['type'=>$type])->find()){
    //             exit;
    //         }else{
    //             $cateId = $category['cateid'];
    //         }
    //     }

    //     $yalimedia = get_addon_config('yalimedia');
    //     $config    = $yalimedia['ali'];
    //     $regionId  = $config['regionId'];

    //     $this->assign('cateId',$cateId);
    //     $this->assign('regionId',$regionId);
    //     $this->assign('cateName',$cateName);
    //     $this->assign('type',$type);

    //     $this->view->engine->layout(false);
    //     switch ($type){
    //         case "1":
    //             return $this->view->fetch();
    //             break;
    //         case "2":
    //         case "3":
    //             return $this->view->fetch();
    //         case "4":
    //             return $this->view->fetch("add_image");
    //     }

    // }

    public function createUploadImage(){

        $titleName = $this->request->get("titleName");
        $cateId = $this->request->get("cateId");
  
        $result = AlibabaCloundHelper::instance()->createUploadImage($titleName,$cateId);

        if($result){
            echo json_encode(['UploadAddress'=>$result->UploadAddress,'ImageId'=>$result->ImageId,'RequestId'=>$result->RequestId,'UploadAuth'=>$result->UploadAuth]);
        }
        exit;
    }

    public function refreshUploadVideo(){
        $videoid = $this->request->get("videoid");

        $result = AlibabaCloundHelper::instance()->RefreshUploadVideo($videoid);
        if($result){
            echo json_encode(['UploadAddress'=>$result->UploadAddress,'VideoId'=>$result->VideoId,'RequestId'=>$result->RequestId,'UploadAuth'=>$result->UploadAuth]);
        }
        exit;
    }

    public function createUploadVideo(){

        $titleName = $this->request->get("titleName");
        $fileName = $this->request->get("fileName");
        $cateId = $this->request->get("cateId");


        $tmpid = "VOD_NO_TRANSCODE";
        $result = AlibabaCloundHelper::instance()->createUploadVideo($titleName,$fileName,$cateId,$tmpid);

        if($result){
            echo json_encode(['UploadAddress'=>$result->UploadAddress,'VideoId'=>$result->VideoId,'RequestId'=>$result->RequestId,'UploadAuth'=>$result->UploadAuth]);
        }
        exit;
    }


    public function tree(){

        $type = $this->request->get('type',2);
        $id = $this->request->get('id');

        if(empty($id) || $id == '#'){
            $categoryModel = new \app\admin\model\yalimedia\Category();
             
            if(!$category = $categoryModel->where(['type'=>$type])->find()){
                exit;
            }else{
                $cateId = $category['cateid'];
            }
        }else{
            $cateId = $id;
        }


        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);

        $chanelList = [];
        if($id=='#'){
            switch ($type){
                case "2":
                    $text = "全部音频";
                    break;
                case "3":
                    $text = "全部视频";
                    break;
                case "1":
                    $text = "全部图片";
                    break;
            }
            $chanelList[$cateId] = ['id'=>$cateId,'type'=>'total','text'=>$text,'parent'=>"#"];
        }

        foreach($list as $k=>$v){
            if($v->SubTotal){
                $children = true;
            }else{
                $children = false;
            }
            
            
            $chanelList[$v->CateId] = ['id'=>$v->CateId,'text'=>$v->CateName,'type'=>"folder",'children'=>$children,'parent'=>$id=='#'?'#':$cateId,'state'=>['opened'=>false]];
        }

        $chanelList = array_values($chanelList);

        return json($chanelList);
    }

    /**
     * 素材上传分组
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upload_tree(){
        $type = $this->request->get('type');
        $id = $this->request->get('id');

        if(empty($id) || $id == '#'){
            $categoryModel = new \app\admin\model\yalimedia\Category();
            if(!$category = $categoryModel->where(['type'=>$type])->find()){
                exit;
            }else{
                $cateId = $category['cateid'];
            }
        }else{
            $cateId = $id;
        }

        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);
        $chanelList = [];
        if($id=='#'){
            $chanelList[$cateId] = ['id'=>$cateId,'text'=>"默认分组",'type'=>'total','parent'=>"#",'state'=>['opened'=>true]];
        }
        foreach($list as $k=>$v){
            if($v->SubTotal){
                $children = true;
            }else{
                $children = false;
            }
            $chanelList[$v->CateId] = ['id'=>$v->CateId,'text'=>$v->CateName,'type'=>'folder','children'=>$children,'parent'=>$id=='#'?'#':$cateId,'state'=>['opened'=>false]];
        }
        $chanelList = array_values($chanelList);

        return json($chanelList);
    }

    
    
    
     /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[cateid]', CourseModel::column('id,title'), $row['cateid'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }
    
    
    
    // /**
    //  * 编辑
    //  */
    // public function edit($ids = NULL)
    // {
    //     if ($this->request->isPost()) {
    //         $params = $this->request->post("row/a");
            
    //         if ($params) {
    //             try {
                    
    //                 $Title  = $params['title'];
    //                 $CateId = $params['cateid'];
    //                 $type   = $params['type'];
    //                 if($type == 1){
    //                     $updateContent[] = ["ImageId"=>$ids,'Title'=>$Title,'CateId'=>$CateId];
    //                     $ret = AlibabaCloundHelper::instance()->update_image(json_encode($updateContent));
    //                 }else{
    //                     $ret = AlibabaCloundHelper::instance()->edit_video($ids,$CateId,$Title);
    //                 }
                    
    //                 if($ret){
    //                     sleep(1);
    //                     $this->success();
    //                 }
    //             } catch (\think\exception\PDOException $e) {
    //                 $this->error($e->getMessage());
    //             } catch (\think\Exception $e) {
    //                 $this->error($e->getMessage());
    //             } catch (ServerException $e){
    //                 $this->error("编辑失败，请检查阿里云服务");
    //             }
    //         }
    //         $this->error(__('Parameter %s can not be empty', ''));
    //     }
        
        
    //     $ids = $this->request->param("ids");
    //     halt($ids);
        
    //     if (!$row){
    //         $this->error(__('No Results were found'));
    //     }
            
            
    //     $adminIds = $this->getDataLimitAdminIds();
    //     if (is_array($adminIds)) {
    //         if (!in_array($row[$this->dataLimitField], $adminIds)) {
    //             $this->error(__('You have no permission'));
    //         }
    //     }



    //     $categoryModel = new \app\admin\model\yalimedia\Category();
    //     if(!$category = $categoryModel->where(['type'=>$type])->find()){
    //         exit;
    //     }else{
    //         $cateId = $category['cateid'];
    //     }
        
        
    //     //查看当前是否已经生成根分类
    //     $list = AlibabaCloundHelper::instance()->categories($cateId);

    //     $this->assign('type',$type);
    //     $this->assign('cateList',$list);

    //     $this->view->assign("row", $row);
    //     return $this->view->fetch();
    // }


}
